from typing import Dict, Any
from intelli_port.commons.config import load_settings
from intelli_port.commons.audit import write_ops_log


class RobotExecutor:
    def navigate_to(self, robot_id: int, target: Dict[str, Any]) -> Dict[str, Any]:
        return {"ok": False}

    def cancel(self, robot_id: int, task_id: int) -> Dict[str, Any]:
        return {"ok": False}

    def status(self, robot_id: int) -> Dict[str, Any]:
        return {"ok": True, "status": "idle"}


class StubRobotExecutor(RobotExecutor):
    def navigate_to(self, robot_id: int, target: Dict[str, Any]) -> Dict[str, Any]:
        write_ops_log("INFO", "robot.navigate", {"robot_id": robot_id, "target": target})
        return {"ok": True, "task_id": int(target.get("task_id") or 0)}

    def cancel(self, robot_id: int, task_id: int) -> Dict[str, Any]:
        write_ops_log("INFO", "robot.cancel", {"robot_id": robot_id, "task_id": task_id})
        return {"ok": True}

    def status(self, robot_id: int) -> Dict[str, Any]:
        return {"ok": True, "status": "moving"}


def create_robot_executor() -> RobotExecutor:
    s = load_settings()
    mode = str(getattr(s, "robot_execution_mode", "stub") or "stub").lower()
    if mode == "ros2":
        try:
            from .ros2_nav2 import Ros2Nav2Executor
            inst = Ros2Nav2Executor()
            if not bool(getattr(inst, "_ready", False)):
                return StubRobotExecutor()
            return inst
        except Exception:
            return StubRobotExecutor()
    return StubRobotExecutor()